import { createRouter, createWebHistory } from "vue-router";
import { ElMessage } from "element-plus";

const routes = [
    {
        path: "/login",
        name: "login",
        component: () => import("../views/LoginView"),
    },
    {
        path: "/",
        redirect: "/login",
    },
    {
        path: "/home",
        name: "home",
        component: () => import("../views/HomeView"),
    },
    {
        path: "/user-manage",
        name: "user-manage",
        component: () => import("../views/manage/UserManage"),
    },
    {
        path: "/order-manage",
        name: "order-manage",
        redirect: "/order-manage/send",
        children: [
            {
                path: "send",
                name: "send",
                component: () => import("../views/manage/order/OrderSend"),
            },
            {
                path: "shipping",
                name: "shipping",
                component: () => import("../views/manage/order/OrderShipping"),
            },
            {
                path: "confirm",
                name: "confirm",
                component: () => import("../views/manage/order/OrderConfirm"),
            },
        ],
    },
    {
        path: "/category-manage",
        name: "category-manage",
        component: () => import("../views/manage/CategoryManage"),
    },
    {
        path: "/book-manage",
        name: "book-manage",
        redirect: "/book-manage/detail",
        children: [
            {
                path: "add",
                name: "addBook",
                component: () => import("../views/manage/book/AddBook"),
            },
            {
                path: "detail",
                name: "bookDetail",
                component: () => import("../views/manage/book/BookManage"),
            },
        ],
    },
    {
        path: "/:pathMatch(.*)*",
        name: "notFound",
        component: () => import("../views/NotFoundView"),
    },
];

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes,
});

router.beforeEach(async (to, from, next) => {
    if (sessionStorage.getItem("token") === null && to.name !== "login") {
        ElMessage({
            type: "error",
            message: "请先登录",
            duration: 3000,
        });
        setTimeout(() => {}, 3000);
        next({ name: "login" });
    }
    if (sessionStorage.getItem("token") && to.name === "login") {
        ElMessage({
            type: "error",
            message: "你已经登陆过了",
            duration: 3000,
        });
        setTimeout(() => {}, 3000);
        next({ name: "home" });
    }
    next();
});

export default router;
